package com.itheima.advantagesup.controller;

import com.itheima.advantagesup.common.R;
import com.itheima.advantagesup.entity.Picture;
import com.itheima.advantagesup.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author iTaotao
 * @version 1.0.0
 * @ClassName UploadController.java
 * @Description 上传接口
 * @createTime 2023年07月29日 10:27:00
 */
@RestController
@Slf4j
@RequestMapping("/common")
public class UploadController {
    @Autowired
    private AliOssUtil aliOssUtil;

    @PostMapping("/upload")
    public R<Map<String , Object>> upload(@RequestBody MultipartFile file) throws IOException {
        log.info("文件上传:{}", file);
        HashMap<String , Object> re = new HashMap<>();
        String originalFilename = file.getOriginalFilename();

        //构建新的文件名
        String extname = originalFilename.substring(originalFilename.lastIndexOf("."));//文件扩展名
        String newFileName = UUID.randomUUID().toString() + extname;//随机名+文件扩展名
        re.put("savePath" , "/1.jpg");
        re.put("name" , newFileName);
        re.put("mime" , "jpg");
        re.put("size" , file.getSize());
        //将文件存储在服务器的磁盘目录
         // file.transferTo(new File("D:/WebDev/youdianda/nginx-youdianda/undefined" + newFileName));

        return R.success(re);


//
//        try {
//            String originalFilename = file.getOriginalFilename();
//
//            String objectName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
//            String url = aliOssUtil.upload(file.getBytes(), objectName);
//            Picture picture = new Picture();
//            picture.setSavePath(url);
//            picture.setName(originalFilename);
//            picture.setMime(file.getContentType());
//            picture.setSize(file.getSize());
//            return R.success(picture);
//        } catch (IOException e) {
//            log.info(e.getMessage(), e);
//            return R.error("上传失败");
//        }


    }
}
